import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/storage'

// 进度条配置
NProgress.configure({ 
  easing: 'ease', 
  speed: 500, 
  showSpinner: false 
})

// 路由白名单，不需要登录即可访问
const whiteList = ['/login', '/register', '/forgot-password']

// 路由配置
const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    redirect: '/dashboard',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/user/Login.vue'),
    meta: { title: '登录', requiresAuth: false },
  },
  // {
  //   path: '/register',
  //   name: 'Register',
  //   component: () => import('@/views/user/Register.vue'),
  //   meta: { title: '注册', requiresAuth: false },
  // },
  {
    path: '/',
    component: () => import('@/layouts/BasicLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        alias: '/dashboard',
        name: 'Dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '控制台', icon: 'dashboard', keepAlive: true },
      },
      // 作业管理路由
      {
        path: 'assignment',
        alias: '/assignment',
        name: 'Assignment',
        component: () => import('@/views/assignment/Index.vue'),
        meta: { title: '作业管理', icon: 'book', role: ['admin', 'teacher'] },
      },
      // 作业编辑路由
      {
        path: 'assignment/edit',
        name: 'AssignmentAdd',
        component: () => import('@/views/assignment/Edit.vue'),
        meta: { title: '新增作业', icon: 'book', role: ['admin', 'teacher'], hideInMenu: true },
      },
      // 作业编辑路由(带ID)
      {
        path: 'assignment/edit/:id',
        name: 'AssignmentEdit',
        component: () => import('@/views/assignment/Edit.vue'),
        meta: { title: '编辑作业', icon: 'book', role: ['admin', 'teacher'], hideInMenu: true },
      },
      // 学生作业管理路由
      {
        path: 'student',
        alias: '/student',
        name: 'Student',
        component: () => import('@/views/student/Index.vue'),
        meta: { title: '学生作业管理', icon: 'solution', role: ['admin', 'teacher', 'student'] },
      },
      // 学生作业详情路由
      {
        path: 'student/detail/:id',
        name: 'StudentDetail',
        component: () => import('@/views/student/Detail.vue'),
        meta: { title: '学生作业详情', hideInMenu: true, role: ['admin', 'teacher', 'student'] },
      },
      // AI批改结果管理路由
      // {
      //   path: 'grading',
      //   alias: '/grading',
      //   name: 'Grading',
      //   component: () => import('@/views/grading/Index.vue'),
      //   meta: { title: 'AI批改结果', icon: 'check-circle', role: ['admin', 'teacher'] },
      // },
      // 用户管理路由
      {
        path: 'user',
        alias: '/user',
        name: 'User',
        component: () => import('@/views/user/Index.vue'),
        meta: { title: '用户管理', icon: 'user', role: ['admin','teacher'] },
      },
      // API密钥管理路由
      {
        path: 'apikey',
        alias: '/apikey',
        name: 'ApiKey',
        component: () => import('@/views/apikey/Index.vue'),
        meta: { title: 'API密钥管理', icon: 'key', role: ['admin', 'teacher', 'student'] },
      },
    ],
  },
  // 404页面
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/NotFound.vue'),
    meta: { title: '404', requiresAuth: false },
  },
]

// 创建路由
const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior: () => ({ left: 0, top: 0 }),
})

// 路由守卫
router.beforeEach((to, _from, next) => {
  // 开始进度条
  NProgress.start()
  
  // 设置标题
  document.title = to.meta.title 
    ? `${to.meta.title} - ${import.meta.env.VITE_APP_TITLE}`
    : import.meta.env.VITE_APP_TITLE
  
  // 判断是否需要登录权限
  const hasToken = getToken()
  
  if (hasToken) {
    // 已登录
    if (to.path === '/login') {
      // 已登录跳转到控制台
      next({ path: '/dashboard' })
      NProgress.done()
    } else {
      // 校验页面权限
      const userRole = localStorage.getItem('userRole') || 'guest'
      const requiredRoles = to.meta.role as string[] | undefined
      if (requiredRoles && !requiredRoles.includes(userRole) && userRole !== 'admin') {
        // 没有权限跳转到404
        next({ path: '/404' })
        NProgress.done()
      } else {
        next()
      }
    }
  } else {
    // 未登录
    if (whiteList.includes(to.path)) {
      // 在白名单中直接跳转
      next()
    } else {
      // 不在白名单中重定向到登录页
      next(`/login?redirect=${to.path}`)
      NProgress.done()
    }
  }
})

// 路由跳转后钩子
router.afterEach(() => {
  // 结束进度条
  NProgress.done()
})

export default router 